<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer" />
    <title>智能电影推荐系统 - 首页</title>
    <!-- 新 Bootstrap5 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark px-3" style="background-color: #0d6efd;">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">智能电影推荐系统</a>
            <div class="d-flex" id="userInfoArea">
                <!-- 用户信息区域将通过JavaScript动态填充 -->
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        <h1>欢迎来到智能电影推荐系统</h1>
        <div class="row mb-4">
            <div class="col-md-5">
                <select id="typeSelect" class="form-select">
                    <option value="">所有类型</option>
                </select>
            </div>
            <div class="col-md-7">
                <div class="input-group">
                    <input type="text" id="searchInput" class="form-control" placeholder="搜索电影...">
                    <button class="btn btn-primary" type="button" id="searchBtn">搜索</button>
                </div>
            </div>
        </div>
        <div id="moviesContainer" class="row"></div>
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center" id="pagination"></ul>
        </nav>
    </div>

    <!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
    <script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="js/common.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            loadTypes();
            const userInfoArea = document.getElementById('userInfoArea');
            const user = JSON.parse(localStorage.getItem('user'));
            const moviesContainer = document.getElementById('moviesContainer');
            const pagination = document.getElementById('pagination');
            let currentPage = 1;
            const perPage = 12;

            function loadTypes() {
                axios.get(`${API_BASE_URL}/regions_types`)
                    .then(response => {
                        const typeSelect = document.getElementById('typeSelect');
                        response.data.types.forEach(type => {
                            const option = document.createElement('option');
                            option.value = type;
                            option.textContent = type;
                            typeSelect.appendChild(option);
                        });
                    })
                    .catch(error => console.error('Error:', error));
            }

            function loadMovies(page, search = '', type = '') {
                axios.get(`${API_BASE_URL}/movies?page=${page}&per_page=${perPage}&search=${search}&type=${type}`)
                    .then(response => {
                        const data = response.data;
                        renderMovies(data.movies);
                        renderPagination(data.pages, page);
                    })
                    .catch(error => console.error('Error:', error));
            }

            function renderMovies(movies) {
                moviesContainer.innerHTML = '';
                movies.forEach(movie => {
                    const movieCol = document.createElement('div');
                    movieCol.className = 'col-md-3 col-sm-6 col-6 mb-4';
                    movieCol.innerHTML = `
                        <a href="movie.html?id=${movie.id}" class="text-decoration-none">
                            <div class="card h-100">
                                <img src="${movie.poster}" class="card-img-top" alt="${movie.title}" referrerpolicy="no-referrer">
                                <div class="card-body p-2">
                                    <h6 class="card-title text-truncate" data-bs-toggle="tooltip" title="${movie.title}">${movie.title}</h6>
                                </div>
                            </div>
                        </a>
                    `;
                    moviesContainer.appendChild(movieCol);
                });
            }

            function renderPagination(totalPages, currentPage) {
                pagination.innerHTML = '';
                
                // 首页按钮
                const firstLi = document.createElement('li');
                firstLi.className = 'page-item' + (currentPage === 1 ? ' disabled' : '');
                firstLi.innerHTML = '<a class="page-link" href="#" aria-label="First"><span aria-hidden="true">首页</span></a>';
                firstLi.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentPage > 1) loadMovies(1);
                });
                pagination.appendChild(firstLi);

                // 上一页按钮
                const prevLi = document.createElement('li');
                prevLi.className = 'page-item' + (currentPage === 1 ? ' disabled' : '');
                prevLi.innerHTML = '<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a>';
                prevLi.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentPage > 1) loadMovies(currentPage - 1);
                });
                pagination.appendChild(prevLi);

                // 页码按钮
                const startPage = Math.max(1, currentPage - 3);
                const endPage = Math.min(totalPages, currentPage + 3);
                
                // 显示第一页
                if (startPage > 1) {
                    const pageLi = document.createElement('li');
                    pageLi.className = 'page-item' + (1 === currentPage ? ' active' : '');
                    pageLi.innerHTML = '<a class="page-link" href="#">1</a>';
                    pageLi.addEventListener('click', (e) => {
                        e.preventDefault();
                        loadMovies(1);
                    });
                    pagination.appendChild(pageLi);
                    
                    if (startPage > 2) {
                        const ellipsisLi = document.createElement('li');
                        ellipsisLi.className = 'page-item disabled';
                        ellipsisLi.innerHTML = '<span class="page-link">...</span>';
                        pagination.appendChild(ellipsisLi);
                    }
                }
                
                // 显示中间页码
                for (let i = startPage; i <= endPage; i++) {
                    if (i === totalPages) continue;
                    
                    const pageLi = document.createElement('li');
                    pageLi.className = 'page-item' + (i === currentPage ? ' active' : '');
                    pageLi.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                    pageLi.addEventListener('click', (e) => {
                        e.preventDefault();
                        loadMovies(i);
                    });
                    pagination.appendChild(pageLi);
                }
                
                // 显示最后一页
                if (endPage < totalPages) {
                    if (endPage < totalPages - 1) {
                        const ellipsisLi = document.createElement('li');
                        ellipsisLi.className = 'page-item disabled';
                        ellipsisLi.innerHTML = '<span class="page-link">...</span>';
                        pagination.appendChild(ellipsisLi);
                    }
                    
                    const pageLi = document.createElement('li');
                    pageLi.className = 'page-item' + (totalPages === currentPage ? ' active' : '');
                    pageLi.innerHTML = `<a class="page-link" href="#">${totalPages}</a>`;
                    pageLi.addEventListener('click', (e) => {
                        e.preventDefault();
                        loadMovies(totalPages);
                    });
                    pagination.appendChild(pageLi);
                }

                // 下一页按钮
                const nextLi = document.createElement('li');
                nextLi.className = 'page-item' + (currentPage === totalPages ? ' disabled' : '');
                nextLi.innerHTML = '<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a>';
                nextLi.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentPage < totalPages) loadMovies(currentPage + 1);
                });
                pagination.appendChild(nextLi);
                
                // 末页按钮
                const lastLi = document.createElement('li');
                lastLi.className = 'page-item' + (currentPage === totalPages ? ' disabled' : '');
                lastLi.innerHTML = '<a class="page-link" href="#" aria-label="Last"><span aria-hidden="true">末页</span></a>';
                lastLi.addEventListener('click', (e) => {
                    e.preventDefault();
                    if (currentPage < totalPages) loadMovies(totalPages);
                });
                pagination.appendChild(lastLi);
                
                // 总页数显示
                const totalLi = document.createElement('li');
                totalLi.className = 'page-item disabled';
                totalLi.innerHTML = `<span class="page-link">共 ${totalPages} 页</span>`;
                pagination.appendChild(totalLi);
            }

            // 初始加载第一页
            loadMovies(currentPage);
            
            document.getElementById('searchInput').addEventListener('input', (e) => {
                loadMovies(1, e.target.value, document.getElementById('typeSelect').value);
            });
            
            document.getElementById('searchBtn').addEventListener('click', () => {
                loadMovies(1, document.getElementById('searchInput').value, document.getElementById('typeSelect').value);
            });
            
            document.getElementById('typeSelect').addEventListener('change', (e) => {
                loadMovies(1, document.getElementById('searchInput').value, e.target.value);
            });
            
            // 处理回车键搜索
            document.getElementById('searchInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    loadMovies(1, document.getElementById('searchInput').value, document.getElementById('typeSelect').value);
                }
            });
            
            if (user) {
                // 已登录状态
                userInfoArea.innerHTML = `
                    <span class="navbar-text me-3 text-white">欢迎您，</span>
                    <a href="profile.html" class="navbar-text text-white">${user.nickname}</a>
                    <span class="navbar-text mx-3">|</span>
                    <a href="#" class="navbar-text text-white" id="logoutBtn">退出</a>
                `;
                
                document.getElementById('logoutBtn').addEventListener('click', function() {
                    localStorage.removeItem('user');
                    window.location.reload();
                });
            } else {
                // 未登录状态
                userInfoArea.innerHTML = '<a href="login.html" class="navbar-text text-white">登录</a>';
            }
        });
    </script>
</body>
</html>